package cn.wubo.base.service.impl;


import cn.wubo.base.entity.RoleEntity;
import cn.wubo.base.entity.UserEntity;
import cn.wubo.base.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    UserRepository userRepository;

    @Value("${custom.admin.username}")
    private String superUsername;
    @Value("${custom.admin.password}")
    private String superPassword;
    @Value("${custom.admin.role}")
    private String superRole;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        username = username.toUpperCase();
        if (superUsername.equals(username)) {
            UserEntity superUser = new UserEntity();
            superUser.setId((long) -1);
            superUser.setUsername(superUsername);
            superUser.setPassword(new BCryptPasswordEncoder().encode(superPassword));
            superUser.setName("超级管理员");

            List<RoleEntity> roleEntities = new ArrayList<>();
            RoleEntity roleEntity = new RoleEntity();
            roleEntity.setId((long) -1);
            roleEntity.setName(superRole);
            roleEntities.add(roleEntity);

            superUser.setAuthorities(roleEntities);
            return superUser;
        }

        return userRepository.findByUsername(username);
    }
}
